package com.afeng.util.common;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.afeng.util.log.LogMessageUtil;

/**
 * 
 * @Description : Base64加密解密
 * @Date        : 2017年11月27日
 * @author      : afeng
 */
public class Base64Util {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(Base64Util.class);

    /**
     * 修改key时，注意位数
     */
    private static final String KEY = "afeng-util000001";
    
    /**
     * 对目标字符串进行加密
     */
    public static String encrypt(String value) {
        try {
            byte[] encrypted = getEncryptCipher().doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            LogMessageUtil logMessageUtil = new LogMessageUtil();
            logMessageUtil.add("errMsg", "加密异常");
        }
        return null;
    }

    /**
     * 对目标字符串进行解密
     */
    public static String decrypt(String encrypted) {
        try {
            byte[] original = getDecryptCipher().doFinal(Base64.decodeBase64(encrypted));
            return new String(original);
        } catch (Exception ex) {
            LogMessageUtil logMessageUtil = new LogMessageUtil();
            logMessageUtil.add("errMsg", "解密异常");
        }

        return null;
    }

    /**
     * 加密器
     */
    private static Cipher getEncryptCipher() {
        try {
            IvParameterSpec iv = new IvParameterSpec(KEY.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            return encryptCipher;
        } catch (Exception e) {
            LogMessageUtil logMessageUtil = new LogMessageUtil();
            logMessageUtil.add("errMsg", "加密器初始化异常");
            LOGGER.error(logMessageUtil.toString(), e);
            return null;
        }
    }

    /**
     * 解密器
     */
    private static Cipher getDecryptCipher() {
        try {
            IvParameterSpec iv = new IvParameterSpec(KEY.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            return decryptCipher;
        } catch (Exception e) {
            LogMessageUtil logMessageUtil = new LogMessageUtil();
            logMessageUtil.add("errMsg", "解密器初始化异常");
            return null;
        }
    }

}
